package com.guigu.work.controller;


import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.guigu.base.entity.CoreOrg;
import com.guigu.base.entity.dto.TransportTripsDto;
import com.guigu.base.entity.dto.TruckDto;
import com.guigu.base.entity.vo.TruckStatusDashboardVO;
import com.guigu.tms.result.R;
import com.guigu.tms.result.ResultCode;
import com.guigu.work.dto.TaskTransportDTO;
import com.guigu.work.entity.TaskTransport;
import com.guigu.work.entity.TransportOrderTask;
import com.guigu.work.entity.vo.TaskTransportDetailsVO;
import com.guigu.work.entity.vo.TaskTransportVO;
import com.guigu.work.feign.BaseFeign;
import com.guigu.work.service.TaskTransportService;
import com.guigu.work.service.TransportOrderTaskService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 运输任务表 前端控制器
 * </p>
 *
 * @author liAo
 * @since 2021-11-09
 */
@Slf4j
@Api(tags = "运输任务操作接口")
@RestController
@RequestMapping("/task-transport")
public class TaskTransportController {
    @Autowired
    private TaskTransportService service;
    @Autowired
    private TransportOrderTaskService totService;
    @Autowired
    private BaseFeign baseFeign;

    /**
     * 新增运输任务
     *
     * @param dto 运输任务信息
     * @return 运输任务信息
     */
    @ApiOperation(value = "添加运输任务", notes = "无ID基础数据+transportOrderIds")
    @PostMapping("save")
    public R<TaskTransportDTO> save(@RequestBody TaskTransportDTO dto) {
        TaskTransport taskTransport = service.saveTaskTransport(dto);
        totSave(dto);
        BeanUtils.copyProperties(taskTransport, dto);
        dto.setId(taskTransport.getId());
        log.info("dto:" + dto);
        return new R<TaskTransportDTO>(ResultCode.SUCCESS_CODE, "新增运输任务", dto);
    }

    /**
     * 修改运输任务信息
     *
     * @param dto 运输任务信息
     * @return 运输任务信息
     */
    @ApiOperation(value = "修改运输任务信息", notes = "带ID")
    @PutMapping("/")
    public TaskTransportDTO updateById(@RequestBody TaskTransportDTO dto) {
        TaskTransport taskTransport = new TaskTransport();
        BeanUtils.copyProperties(dto, taskTransport);
        //修改运输任务信息
        service.updateById(taskTransport);
        //删除旧运单与运输任务关系
        totService.deleteBytoIdOrttId(null, dto.getId());
        //添加新关系
        totSave(dto);
        return dto;
    }

    public void totSave(TaskTransportDTO dto) {
        //保存与运单的关联关系
        if (dto.getTransportOrderIds() != null && dto.getTransportOrderIds().size() > 0) {
            List<TransportOrderTask> transportOrderTaskList = dto.getTransportOrderIds().stream().map(transportOrderId -> {
                TransportOrderTask transportOrderTask = new TransportOrderTask();
                transportOrderTask.setTransportOrderId(transportOrderId);
                transportOrderTask.setTransportTaskId(dto.getId());
                return transportOrderTask;
            }).collect(Collectors.toList());
            totService.saveOrUpdateBatch(transportOrderTaskList);
        }
    }


    /**
     * 获取运输任务分页数据
     *
     * @param pageNum  页码
     * @param pageSize 页数
     * @return
     */
    @ApiOperation(value = "获取运输任务分页数据", notes = "page&pageSize&id&status")
    @GetMapping("/findByPage/{pageNum}/{pageSize}")
    public R<Page<TaskTransportVO>> findByPage(@PathVariable("pageNum") String pageNum,
                                               @PathVariable("pageSize") String pageSize) {
        IPage<TaskTransport> q = new Page<>();
        q.setSize(Long.valueOf(pageSize));
        q.setCurrent(Long.valueOf(pageNum));
        IPage<TaskTransport> page = service.page(q, null);
        log.info("为转换之前的pageList为:{},总页数为:{},页数为 :{},页码为:{},总数为:{}", page.getRecords(), page.getPages(), page.getSize(), page.getCurrent(), page.getTotal());
        List<TaskTransportVO> list = page.getRecords().stream().map(t -> {
            TaskTransportVO taskTransportVO = new TaskTransportVO();
            BeanUtil.copyProperties(t, taskTransportVO);
            CoreOrg startData = baseFeign.findCoreOrgById(t.getStartAgencyId()).getData();
            CoreOrg endData = baseFeign.findCoreOrgById(t.getEndAgencyId()).getData();
            TruckDto truckDto = baseFeign.findTruckById(t.getTruckId()).getData();
            TransportTripsDto tripsDto = baseFeign.fineTripsById(t.getTransportTripsId()).getData();
            taskTransportVO.setStartAgencyName(startData.getName());
            taskTransportVO.setEndAgencyName(endData.getName());
            taskTransportVO.setTruckName(truckDto.getBrand());
            taskTransportVO.setTransportTripsName(tripsDto.getName());
            return taskTransportVO;
        }).collect(Collectors.toList());
        Page<TaskTransportVO> voPage = new Page<>();
        voPage.setRecords(list);
        voPage.setSize(page.getSize());
        voPage.setCurrent(page.getCurrent());
        voPage.setPages(page.getPages());
        voPage.setTotal(page.getTotal());
        return new R<>(ResultCode.SUCCESS_CODE, voPage);
    }

    /**
     * 获取运单列表
     *
     * @param dto 查询条件
     * @return 运单列表
     */
    @ApiOperation(value = "获取运单列表", notes = "ids&Id&status&truckId")
    @PostMapping("/list")
    public R<TaskTransportDTO> findAll(@RequestBody TaskTransportDTO dto) {
        List<TaskTransport> transports = service.findAll(dto);

        return new R(ResultCode.SUCCESS_CODE, "获取运单列表成功!", transports);

    }

    /**
     * 根据运单id或运输任务id获取运输任务列表
     *
     * @return 运输任务列表
     */
    @ApiOperation(value = "根据运单id或运输任务id获取运输任务列表", notes = "transportOrderId||taskTransportId")
    @GetMapping("/listByOrderIdOrTaskId")
    public R<TaskTransport> findAllByOrderIdOrTaskId(@RequestParam(name = "transportOrderId", required = false) String transportOrderId,
                                                     @RequestParam(name = "taskTransportId", required = false) String taskTransportId) {
        List<TransportOrderTask> transportOrderTaskList = totService.findAll(transportOrderId, taskTransportId);
        List<String> transportTaskIds = transportOrderTaskList.stream().map(transportOrderTask -> transportOrderTask.getTransportTaskId()).collect(Collectors.toList());
        List<TaskTransport> dtoList = new ArrayList<>();
        TaskTransportDTO dto = new TaskTransportDTO();

        if (transportTaskIds != null && transportTaskIds.size() > 0) {
            dto.setTransportOrderIds(transportTaskIds);
            dtoList = service.findAll(dto);
        }

        return new R(ResultCode.SUCCESS_CODE, "根据运单id或运输任务id获取运输任务列表成功!",
                dtoList);
    }

    /**
     * 根据id获取运输任务信息
     *
     * @param id 运输任务id
     * @return 运输任务信息
     */
    @ApiOperation(value = "根据id获取运输任务信息", notes = "id")
    @GetMapping("/{id}")
    public R<TaskTransportDTO> findById(@PathVariable(name = "id") String id) {
        TaskTransportDTO dto = new TaskTransportDTO();
        TaskTransport taskTransport = service.getById(id);

        if (taskTransport != null) {
            BeanUtils.copyProperties(taskTransport, dto);
            List<String> transportOrderIds = new ArrayList<>();
            List<TransportOrderTask> transportOrderTaskList = totService.findAll(null, taskTransport.getId());
            transportOrderIds.addAll(transportOrderTaskList.stream().map(transportOrderTask -> transportOrderTask.getTransportOrderId()).collect(Collectors.toList()));
            dto.setTransportOrderIds(transportOrderIds);
        } else {
            dto = null;
        }
        return new R(ResultCode.SUCCESS_CODE, "根据id获取运输任务信息成功!",
                dto);
    }

    /**
     * 根据运输任务id查询运单详情
     *
     * @param id
     * @return
     */
    @ApiOperation("根据运输任务id查询运单详情")
    @GetMapping("/findTransportDetailsById/{id}")
    public R<TaskTransportDetailsVO> findTransportDetailsById(@PathVariable String id) {
        TaskTransportDetailsVO vo = service.findTransportDetailsById(id);
        return new R<>(ResultCode.SUCCESS_CODE, vo);
    }

    /**
     * 获取车载状态数
     *
     * @return
     */
    @GetMapping("/getTruckStatusCount")
    @ApiOperation("获取车载状态数")
    public R<TruckStatusDashboardVO> getTruckStatusCount() {
        TruckStatusDashboardVO vo = service.getTruckStatusCount();
        return new R<>(ResultCode.SUCCESS_CODE, vo);
    }
}

